# -*- encoding: utf-8 -*-
"""
@File:        DatasourceDao.py
@Author:      Little duo
@Time:        2024/4/12 11:30
@Contact:     1049041957@qq.com
"""

from sqlalchemy.orm import Session

from . import Datasource, DatasourcePageQueryModel, DatasourceModel, DeleteDatasourceModel
from utils.page_util import PageUtil
from datetime import datetime, time


class DatasourceDao:

    @classmethod
    def getDatasourceById(cls, db: Session, datasource_id: int):
        data = db.query(Datasource).filter(Datasource.datasource_id == datasource_id, Datasource.status == 0).first()
        return data

    @classmethod
    def getDatasourceList(cls, db: Session, obj: DatasourcePageQueryModel, is_page: bool = False):
        query = db.query(Datasource)
        query.filter(Datasource.status == 0)
        if obj.datasource_name:
            query.filter(Datasource.datasource_name.like(f'%{obj.datasource_name}%'))
        data = PageUtil.paginate(query, obj.page_num, obj.page_size, is_page)
        return data

    @classmethod
    def addDatasource(cls, db: Session, obj: DatasourceModel):
        data = Datasource(**obj.model_dump())
        db.add(data)
        db.flush()
        return data

    @classmethod
    def updateDatasource(cls, db: Session, obj: dict):
        db.query(Datasource).filter(Datasource.datasource_id == obj.get('datasource_id')).update(obj)
        db.flush()
        return True

    @classmethod
    def deleteDatasource(cls, db: Session, datasource_id):
        db.query(Datasource).filter(Datasource.datasource_id == datasource_id).delete()
        db.flush()
        return True

